package org.will.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by EdifierWill on 2016/8/9.
 */
public class DemoMsgConsumer implements MessageListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoMsgConsumer.class);
    private static final String BROKER_URL = "tcp://10.3.4.165:61616";
    private static final String SUBJECT = "willmqdemoQueue";//"test-activemq-queue";
    //private static final String TOPIC = "test-activemq-topic";
    private String _name;

    public static void ConsumeMsg(int consumerCount) throws Throwable {

        //初始化连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
        //获得连接
        Connection conn = connectionFactory.createConnection();
        //启动连接
        conn.start();

        //创建Session，此方法第一个参数表示会话是否在事务中执行，第二个参数设定会话的应答模式
        Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        for(int i=0;i<consumerCount;i++)
        {
            //创建队列目标
            Destination dest = session.createQueue(SUBJECT);
            //创建消息生产者
            MessageConsumer consumer = session.createConsumer(dest);
            //初始化MessageListener
            DemoMsgConsumer msgConsumer = new DemoMsgConsumer("Consumer-"+i);
            consumer.setMessageListener(msgConsumer);
        }
    }

    public DemoMsgConsumer(String name)
    {
        this._name = name;
    }

    /**
     * 消费者需要实现MessageListener接口
     * 接口有一个onMessage(Message message)需要在此方法中做消息的处理
     */
    public void onMessage(Message msg) {
        TextMessage txtMessage = (TextMessage)msg;
        try {
            String xmlStr = txtMessage.getText();
            Operation operation =  OperationFactory.create(xmlStr);
            System.out.println(_name + " operation message:" + operation.getTable());
            OperationModule.justDo(operation);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
